package com.pignest.hotel.ui.room;

import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.OpenEvent;
import org.zkoss.zul.Menuitem;
import org.zkoss.zul.Menupopup;

import com.pignest.hotel.beans.Room;
import com.pignest.hotel.definition.RoomLiveStatus;
import com.pignest.hotel.definition.RoomRepairStatus;
import com.pignest.hotel.definition.RoomUseStatus;
import com.pignest.hotel.service.RoomService;
import com.pignest.hotel.spring.Services;
import com.pignest.hotel.system.L;
import com.pignest.hotel.system.Logic;

public class RoomContextMenu extends Menupopup implements EventListener {
	
	private static final long serialVersionUID = 7443250500678626491L;
	private RoomView roomView;
	private Room room;

	public RoomContextMenu() {
		addEventListener("onOpen", this);
	}
	
	@Override
	public void onEvent(Event event) throws Exception {
		if ("onOpen".equals(event.getName())) {
			OpenEvent ev = (OpenEvent)event;
			if (ev.isOpen() && ev.getReference() instanceof RoomView) {
				RoomView r = (RoomView)ev.getReference();
				onOpen(r);
//			} else {
//				roomView = null;
//				room = null;
//				((Menuitem)getFellow("title")).setLabel(null);
			}
		}
	}
	
	protected void onOpen(RoomView rv) {
		roomView = rv;
		room = rv.getRoom();
		((Menuitem)getFellow("title")).setLabel(room.getName());
	}
	
	public Room getRoom() {
		return room;
	}
	
	public String getRoomId() {
		return room == null ? null : room.getId();
	}
	
	public void setUseStatus(RoomUseStatus status) {
		if (!Logic.canChangeStatus(room, status))
			return;
		room.setRoomUseStatus(status);
		update();
	}

	public void setLiveStatus(RoomLiveStatus status) {
		if (!Logic.canChangeStatus(room, status))
			return;
		room.setLiveStatus(status.name());
		update();
	}

	public void setRepairStatus(RoomRepairStatus status) {
		if (!Logic.canChangeStatus(room, status))
			return;
		room.setRepairStatus(status.name());
		update();
	}

//	public void setUseStatus(boolean clean) {
//		if (room == null)
//			return;
//		room.setUseStatus(clean ? RoomUseStatus.CLEAN.name() : RoomUseStatus.DIRTY.name());
//		update();
//	}
//	
//	public void setLiveStatus(boolean live) {
//		if (room == null)
//			return;
//		room.setLiveStatus(live ? RoomLiveStatus.FILLED.name() : RoomLiveStatus.EMPTY.name());
//		update();
//	}
//	
//	public void setRepairStatus(boolean repair) {
//		if (room == null)
//			return;
//		room.setRepairStatus(repair ? RoomRepairStatus.REPAIR.name() : RoomRepairStatus.NORMAL.name());
//		update();
//	}
	
	private void update() {
		RoomService service = Services.getRoomService();
		service.updateRoom(room);
		L.update(room);
		refreshCurrentRoom();
	}
	
	public void refreshCurrentRoom() {
		if (roomView != null)
			roomView.update();
	}
}
